<template>
  <div class="user-followers-list">
    <div class="list-header">
      <h3>粉丝列表</h3>
      <span class="count">{{ followers.length }} 人</span>
    </div>

    <div v-loading="loading" class="user-list">
      <div v-if="followers.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无粉丝" />
      </div>

      <div v-else class="user-grid">
        <div
          v-for="user in followers"
          :key="user.userId"
          class="user-card"
          @click="handleUserClick(user)"
        >
          <div class="user-avatar">
            <el-avatar :size="60" :src="formatAvatarUrl(user.avatar)">
              <el-icon :size="30"><UserFilled /></el-icon>
            </el-avatar>
          </div>

          <div class="user-info">
            <div class="user-name">
              <h4>{{ user.nickName }}</h4>
            </div>

            <div class="user-stats">
              <span class="stat-item">{{ user.articleCount }} 文章</span>
              <span class="stat-item"
                >{{ formatNumber(user.followerCount) }} 粉丝</span
              >
            </div>

            <div class="follow-time">
              关注于 {{ formatTime(user.followTime) }}
            </div>

            <div v-if="user.isFollowBack" class="follow-back">
              <el-tag size="small" type="success">互相关注</el-tag>
            </div>
          </div>

          <div v-if="isCurrentUser" class="user-actions">
            <el-button
              v-if="!user.isFollowBack"
              size="small"
              type="primary"
              @click.stop="handleFollowBack(user)"
            >
              回关
            </el-button>
            <el-button
              v-else
              size="small"
              type="default"
              @click.stop="handleUnfollow(user)"
            >
              已关注
            </el-button>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { UserFilled } from "@element-plus/icons-vue";
import { useUserAuthStore } from "@/store/modules/userAuth";
import { followUserApi, formatNumber, formatTime } from "@/api/user-profile";
import { useUserFollowers } from "@/composables/useUserInteractions";
import { formatAvatarUrl } from "@/utils/avatar";
import type { FollowerUser } from "@/types/user-interactions";

interface Props {
  userId: number | null;
}

const props = defineProps<Props>();
const router = useRouter();
const userAuthStore = useUserAuthStore();

// 使用用户粉丝数据管理
const {
  loading,
  data,
  currentPage,
  pageSize,
  loadData,
  handlePageChange,
  handleSizeChange
} = useUserFollowers(props.userId!);

// 计算属性
const isCurrentUser = computed(() => props.userId === userAuthStore.userId);
const followers = computed(() => data.value?.records || []);
const total = computed(() => data.value?.total || 0);

const handleUserClick = (user: FollowerUser) => {
  console.log(`👤 跳转到用户主页: ${user.userId}`);
  router.push(`/user/profile/${user.userId}`);
};

const handleFollowBack = async (user: FollowerUser) => {
  try {
    const response = await followUserApi({
      userId: user.userId,
      isFollow: true
    });

    if (response.code === 200) {
      // 直接本地更新：标记为互关
      user.isFollowBack = true;
      ElMessage.success("关注成功");
    } else {
      ElMessage.error(response.message || "关注失败");
    }
  } catch (error) {
    console.error("关注失败:", error);
    ElMessage.error("关注失败");
  }
};

const handleUnfollow = async (user: FollowerUser) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消关注 ${user.nickName} 吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await followUserApi({
      userId: user.userId,
      isFollow: false
    });

    if (response.code === 200) {
      // 直接本地更新：取消互关
      user.isFollowBack = false;
      ElMessage.success("取消关注成功");
    } else {
      ElMessage.error(response.message || "取消关注失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消关注失败:", error);
      ElMessage.error("取消关注失败");
    }
  }
};

// 监听用户ID变化，加载粉丝数据
watch(
  () => props.userId,
  newUserId => {
    console.log(`👥 UserFollowersList - 用户ID变化: ${newUserId}`);
    if (newUserId) {
      loadData(1);
    }
  },
  { immediate: true }
);

onMounted(() => {
  // 移除手动调用，依靠 watch immediate: true 来加载数据
});
</script>

<style lang="scss" scoped>
// 卡片悬停动画
@keyframes card-hover {
  from {
    box-shadow: 0 2px 8px rgb(64 158 255 / 10%);
    transform: translateY(0);
  }

  to {
    box-shadow: 0 8px 24px rgb(64 158 255 / 15%);
    transform: translateY(-5px);
  }
}

// 响应式设计
@media (width <= 768px) {
  .user-followers-list {
    .list-header {
      padding: 16px;

      h3 {
        font-size: 16px;
      }

      .count {
        font-size: 13px;
      }
    }

    .user-list {
      .user-grid {
        grid-template-columns: 1fr;
        gap: 14px;
      }

      .user-card {
        padding: 18px;

        .user-avatar {
          :deep(.el-avatar) {
            width: 50px;
            height: 50px;
          }
        }

        .user-info {
          .user-name {
            h4 {
              font-size: 15px;
            }
          }

          .user-stats {
            gap: 10px;

            .stat-item {
              font-size: 11px;
            }
          }
        }

        .user-actions {
          :deep(.el-button) {
            padding: 8px 14px;
            font-size: 13px;
          }
        }
      }
    }
  }
}

.user-followers-list {
  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #fff 0%, #f8f9ff 100%);
    border-radius: 16px;
    box-shadow: 0 2px 12px rgb(64 158 255 / 8%);

    h3 {
      margin: 0;
      font-size: 20px;
      font-weight: 700;
      color: #303133;
      letter-spacing: 0.5px;
    }

    .count {
      padding: 6px 16px;
      font-size: 14px;
      font-weight: 600;
      color: #409eff;
      background: linear-gradient(
        135deg,
        rgb(64 158 255 / 10%) 0%,
        rgb(103 194 58 / 10%) 100%
      );
      border: 1px solid rgb(64 158 255 / 20%);
      border-radius: 20px;
    }
  }

  .user-list {
    min-height: 300px;

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 300px;
      padding: 40px;
      background: linear-gradient(135deg, #f8f9ff 0%, #fff 100%);
      border-radius: 16px;
    }

    .user-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
      gap: 20px;
    }

    .pagination-container {
      display: flex;
      grid-column: 1 / -1;
      justify-content: center;
      padding: 32px 0 16px;
      margin-top: 20px;

      :deep(.el-pagination) {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        justify-content: center;
      }
    }

    .user-card {
      display: flex;
      gap: 18px;
      align-items: flex-start;
      padding: 24px;
      cursor: pointer;
      background: #fff;
      border: 1px solid rgb(64 158 255 / 15%);
      border-radius: 16px;
      box-shadow: 0 2px 8px rgb(64 158 255 / 8%);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        border-color: #409eff;
        box-shadow: 0 8px 24px rgb(64 158 255 / 15%);
        transform: translateY(-5px);

        .user-avatar {
          :deep(.el-avatar) {
            box-shadow: 0 4px 12px rgb(64 158 255 / 30%);
            transform: scale(1.05);
          }
        }

        .user-info .user-name h4 {
          color: #409eff;
        }
      }

      .user-avatar {
        flex-shrink: 0;

        :deep(.el-avatar) {
          border: 3px solid rgb(64 158 255 / 10%);
          transition: all 0.3s ease;
        }
      }

      .user-info {
        flex: 1;
        min-width: 0;

        .user-name {
          margin-bottom: 10px;

          h4 {
            margin: 0 0 6px;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 17px;
            font-weight: 700;
            color: #303133;
            letter-spacing: 0.3px;
            white-space: nowrap;
            transition: color 0.3s ease;
          }

          .username {
            font-size: 12px;
            color: #909399;
          }
        }

        .user-stats {
          display: flex;
          gap: 16px;
          align-items: center;
          padding: 8px 0;
          margin-bottom: 10px;
          border-top: 1px solid rgb(64 158 255 / 8%);
          border-bottom: 1px solid rgb(64 158 255 / 8%);

          .stat-item {
            font-size: 13px;
            font-weight: 500;
            color: #606266;

            &:not(:last-child)::after {
              margin-left: 16px;
              color: rgb(64 158 255 / 30%);
              content: "|";
            }
          }
        }

        .follow-time {
          margin-bottom: 8px;
          font-size: 12px;
          font-style: italic;
          color: #909399;
        }

        .follow-back {
          margin-top: 8px;

          :deep(.el-tag) {
            font-weight: 600;
            border-radius: 12px;
          }
        }
      }

      .user-actions {
        flex-shrink: 0;
        align-self: center;

        :deep(.el-button) {
          font-weight: 600;
          border-radius: 20px;
          transition: all 0.3s ease;

          &:active {
            transform: scale(0.97);
          }

          &.el-button--primary {
            background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
            border: none;

            &:hover {
              background: linear-gradient(135deg, #53a8ff 0%, #85ce61 100%);
              box-shadow: 0 4px 12px rgb(64 158 255 / 40%);
            }
          }

          &.el-button--default {
            border: 1px solid rgb(64 158 255 / 30%);

            &:hover {
              color: #409eff;
              background: rgb(64 158 255 / 5%);
              border-color: #409eff;
            }
          }
        }
      }
    }
  }
}

// 暗色模式适配
html.dark {
  .user-followers-list {
    .list-header {
      background: linear-gradient(135deg, #1d1e1f 0%, #252627 100%);

      h3 {
        color: #e5eaf3;
      }

      .count {
        color: #67c23a;
        background: linear-gradient(
          135deg,
          rgb(64 158 255 / 15%) 0%,
          rgb(103 194 58 / 15%) 100%
        );
        border-color: rgb(103 194 58 / 30%);
      }
    }

    .user-list {
      .empty-state {
        background: linear-gradient(135deg, #1d1e1f 0%, #252627 100%);
      }

      .user-card {
        background: #1d1e1f;
        border-color: rgb(64 158 255 / 20%);

        .user-info {
          .user-name h4 {
            color: #e5eaf3;
          }

          .user-stats {
            border-color: rgb(64 158 255 / 15%);

            .stat-item {
              color: #a8abb2;
            }
          }
        }
      }
    }
  }
}
</style>
